import fcntl
import io
import time

with open("file.txt", "w+") as file:
    try:
        fcntl.flock(file.fileno(), fcntl.LOCK_EX)  # 获取独占锁
        print("flock 独占文件成功",time.time())
        file.seek(0)
        file.write("Some data")
        time.sleep(10)
    finally:
        fcntl.flock(file.fileno(), fcntl.LOCK_UN)  # 释放锁
